/* Copyright 2008. All rights reserved. */
package org.bling.parser.tags;

import java.util.Collection;
import java.util.Iterator;

import org.bling.parser.BlingParserException;
import org.eclipse.swt.widgets.Widget;

/**
 * Tag that gives looping capability on an array
 * 
 * @author DISBROB
 * 
 */
public class ForEachTag extends Tag {

	private String items;
	private String var;
	private Iterator iterator = null;
	
	public void setItems(String items) {
		this.items = items;
	}

	public void setVar(String var) {
		this.var = var;
	}

	public int doStartTag() throws BlingParserException {
		// Load the array data into the table
		Object obj = evaluate(items);
		if (obj != null && obj instanceof Collection) {
			iterator = ((Collection) obj).iterator();
		}

		if (iterator != null && iterator.hasNext()) {
		   Object value = iterator.next();
		   context.setAttribute(var, value);
		   return EVAL_PAGE;
		}
		
		return SKIP_BODY;
	}

	@Override
	public int doAfterBody() throws BlingParserException {

		if (iterator.hasNext()) {
			Object value = iterator.next();
			context.setAttribute(var, value);
			return EVAL_BODY_AGAIN;	
		}
		
		return EVAL_PAGE;
	}

	@Override
	public Widget getWidget() throws BlingParserException {
		return parent.getWidget();
	}

}
